<?php
function set_config($config)
{
	if(!is_array($config)) return FALSE;
	$configfile = PINGCO_ROOT.'/inc/config.inc.php';
	if(!is_writable($configfile)) showmessage('Please chmod ./inc/config.inc.php to 0777 !');
	$pattern = $replacement = array();
	foreach($config as $k=>$v)
	{
		$pattern[$k] = "/define\(\s*['\"]".strtoupper($k)."['\"]\s*,\s*([']?)[^']*([']?)\s*\)/is";
        $replacement[$k] = "define('".$k."', \${1}".$v."\${2})";
	}
	$str = file_get_contents($configfile);
	$str = preg_replace($pattern, $replacement, $str);
	return file_put_contents($configfile, $str);
}

function showpage ($records,$currentpage,$rows=20,$listpages=7) {
	if($records<1)return '';
	if($rows<1)$rows=20;
	
	if($listpages<3)$listpages=7;
	$action=$_SERVER['QUERY_STRING'];    //得到地址栏中？后的内容

	if($action){  //将page=...的内容去掉
		$action=preg_replace("/&page\b[^\&]*/","",$action);
		$action=preg_replace("/\bpage\b[^\&]*\&*/","",$action);
	}

	if($action)$action.='&amp;';
	$maxpage=ceil($records/$rows);    //进一法取整得到最大页数。
	$middlepage=floor($listpages/2);  //舍去法取整得到要显示的页数的一半。
	
	if($currentpage<1||$currentpage>$maxpage)$currentpage=1;
	$startpage=$currentpage-$middlepage;
	
	if($maxpage-$currentpage<=$middlepage)$startpage=$maxpage-$listpages;
	if($startpage<2)$startpage=1;  //开始页计算完成
	
	$endpage=$startpage+$listpages;
	if($endpage>$maxpage)$endpage=$maxpage;    //结束页计算完成

	//判断上一页
	if($maxpage==1 || $maxpage==2 || $currentpage==1){
		$prepage = 1;
	}else{
		$prepage = $currentpage -1;
	}
	//判断下一页
	if($maxpage==1 || $currentpage==$maxpage){
		$nextpage = $maxpage;
	}else{
		$nextpage = $currentpage +1;
	}

	$pagestr="<a href='?{$action}page=1'>首页</a> ";
	$pagestr.="<a href='?{$action}page=$prepage'><span>上一页</span></a> ";
	$pagestr.="<a href='?{$action}page=$nextpage'><span>下一页</span></a> ";

	$pagestr.="<a href='?{$action}page=$maxpage'>尾页</a>";

	$pagestr.="&nbsp;&nbsp;页次<span>{$currentpage}/{$maxpage}</span>&nbsp;&nbsp;总数<span>{$records}</span>";
	return $pagestr;
}

function showpagepingco ($records,$currentpage,$rows=20,$listpages=7) {
	if($records<1)return '';
	if($rows<1)$rows=20;
	
	if($listpages<3)$listpages=7;
	$action=$_SERVER['QUERY_STRING'];    //得到地址栏中？后的内容

	if($action){  //将page=...的内容去掉
		$action=preg_replace("/&page\b[^\&]*/","",$action);
		$action=preg_replace("/\bpage\b[^\&]*\&*/","",$action);
	}

	if($action)$action.='&amp;';
	$maxpage=ceil($records/$rows);    //进一法取整得到最大页数。
	$middlepage=floor($listpages/2);  //舍去法取整得到要显示的页数的一半。
	
	if($currentpage<1||$currentpage>$maxpage)$currentpage=1;
	$startpage=$currentpage-$middlepage;
	
	if($maxpage-$currentpage<=$middlepage)$startpage=$maxpage-$listpages;
	if($startpage<2)$startpage=1;  //开始页计算完成
	
	$endpage=$startpage+$listpages;
	if($endpage>$maxpage)$endpage=$maxpage;    //结束页计算完成

	//判断上一页
	if($maxpage==1 || $maxpage==2 || $currentpage==1){
		$prepage = 1;
	}else{
		$prepage = $currentpage -1;
	}
	//判断下一页
	if($maxpage==1 || $currentpage==$maxpage){
		$nextpage = $maxpage;
	}else{
		$nextpage = $currentpage +1;
	}

	$pagestr="<a href='".SITE_URL."index.php?{$action}page=1'>首页</a> ";
	$pagestr.="<a href='".SITE_URL."index.php?{$action}page=$prepage'><span>上一页</span></a> ";
	$pagestr.="<a href='".SITE_URL."index.php?{$action}page=$nextpage'><span>下一页</span></a> ";

	$pagestr.="<a href='".SITE_URL."index.php?{$action}page=$maxpage'>尾页</a>";

	$pagestr.="&nbsp;&nbsp;页次<span>{$currentpage}/{$maxpage}</span>";
	return $pagestr;
}







function tpl($file = 'index')
{
	return PINGCO_ROOT.'/templates/'.$file.'.tpl.php';
}

function admintpl($file = 'index')
{
	return PINGCO_ROOT.'/admin/templates/'.$file.'.tpl.php';
}

function showmessage($msg, $url_forward = 'goback', $ms = 1250)
{
	if($url_forward && $url_forward != 'goback' && $url_forward != 'close') $url_forward = url($url_forward, 1);
	if($url_forward && $url_forward!='goback')
	{
		//header("location:$url_forward");
		//exit("<script>self.location='$url_forward';</script>");
	}
	include tpl('showmessage');
	exit;
}

function message($msg, $url_forward = '')
{
	global $mod;
	$url_forward = !empty($url_forward) ? SITE_URL.$url_forward : SITE_URL.'index.php?mod='.$mod;
	$echomsg = '<html><head><title>角色公园 - 提示</title><meta http-equiv="Refresh" content="1; URL='.$url_forward.'" /></head><body>';
	$echomsg .= $msg.'<br />';
	$echomsg .=  '<a href="'.$url_forward.'">返回</a>';
	$echomsg .= '</body></html>';
	echo $echomsg;
	exit;
}

function url($url)
{
	if(strpos($url, '://') !== FALSE || $url[0] == '?') return $url;
	$url = strpos($url, PINGCO_ROOT) === 0 ? $url : PINGCO_ROOT.$url;
	return $url;
}

/**
* get page number for current request
* @return  int
*/
function get_page()
{
	$page = 0;
	if (isset($_GET['page']))
	{
		$page = intval($_GET['page']);
	}
	if ($page <= 0)
	{
		$page = 1;
	}
	return $page;
}
    
function new_htmlspecialchars($string)
{
	return is_array($string) ? array_map('new_htmlspecialchars', $string) : htmlspecialchars($string, ENT_QUOTES);
}

function new_addslashes($string)
{
	if(!is_array($string)) return addslashes($string);
	foreach($string as $key => $val) $string[$key] = new_addslashes($val);
	return $string;
}

function new_stripslashes($string)
{
	if(!is_array($string)) return stripslashes($string);
	foreach($string as $key => $val) $string[$key] = new_stripslashes($val);
	return $string;
}


function format_textarea($string)
{
	return nl2br(str_replace(' ', '&nbsp;', htmlspecialchars($string)));
}

function format_js($string, $isjs = 1)
{
	$string = addslashes(str_replace(array("\r", "\n"), array('', ''), $string));
	return $isjs ? 'document.write("'.$string.'");' : $string;
}

if(!function_exists('file_put_contents'))
{
	define('FILE_APPEND', 8);
	function file_put_contents($file, $data, $append = '')
	{
		$mode = $append == '' ? 'wb' : 'ab';
		$fp = @fopen($file, $mode) or exit("Can not open file $file !");
		flock($fp, LOCK_EX);
		$len = @fwrite($fp, $data);
		flock($fp, LOCK_UN);
		@fclose($fp);
		return $len;
	}
}

if(!function_exists('http_build_query'))
{
    function http_build_query($data, $prefix = null, $sep = '', $key = '')
	{
        $ret = array();
		foreach((array)$data as $k => $v)
		{
			$k = urlencode($k);
			if(is_int($k) && $prefix != null)
			{
				$k = $prefix.$k;
			}
			if(!empty($key)) {
				$k = $key."[".$k."]";
			}
			if(is_array($v) || is_object($v))
			{
				array_push($ret,http_build_query($v,"",$sep,$k));
			}
			else
			{
				array_push($ret,$k."=".urlencode($v));
			}
		}
        if(empty($sep))
		{
            $sep = ini_get("arg_separator.output");
        }
        return implode($sep, $ret);
    }
}

if(!function_exists('image_type_to_extension'))
{
    function image_type_to_extension($type, $dot = true)
    {
        $e = array ( 1 => 'gif', 'jpeg', 'png', 'swf', 'psd', 'bmp' ,'tiff', 'tiff', 'jpc', 'jp2', 'jpf', 'jb2', 'swc', 'aiff', 'wbmp', 'xbm');
        $type = intval($type);
        if (!$type)
		{
            trigger_error( 'File Type is null...', E_USER_NOTICE );
            return null;
        }
        if(!isset($e[$type]))
		{
            trigger_error( 'Image type is wrong...', E_USER_NOTICE );
            return null;
        }
        return ($dot ? '.' : '') . $e[$type];
    }
}

if(!function_exists('array_intersect_key'))
{
	function array_intersect_key($isec, $keys)
	{
		$argc = func_num_args();
		if ($argc > 2)
		{
			for ($i = 1; !empty($isec) && $i < $argc; $i++)
			{
				$arr = func_get_arg($i);
				foreach (array_keys($isec) as $key)
				{
					if (!isset($arr[$key]))
					{
						unset($isec[$key]);
					}
				}
			}
			return $isec;
		}
		else
		{
			$res = array();
			foreach (array_keys($isec) as $key)
			{
				if (isset($keys[$key]))
				{
					$res[$key] = $isec[$key];
				}
			}
			return $res;
		}
	}
}

if(!function_exists('json_encode'))
{
	function json_encode($string)
	{
		require_once 'json.class.php';
		$json = new json();
		return $json->encode($string);
	}
}

if(!function_exists('json_decode'))
{
	function json_decode($string,$type = 1)
	{
		require_once 'json.class.php';
		$json = new json();
		return $json->decode($string,$type);
	}
}

if(!function_exists('iconv'))
{
	function iconv($in_charset, $out_charset, $str)
	{
		if(function_exists('mb_convert_encoding'))
		{
			return mb_convert_encoding($str, $out_charset, $in_charset);
		}
		else
		{

			require_once 'iconv.func.php';
			$in_charset = strtoupper($in_charset);
			$out_charset = strtoupper($out_charset);
			if($in_charset == 'UTF-8' && ($out_charset == 'GBK' || $out_charset == 'GB2312'))
			{
				return utf8_to_gbk($str);
			}
			if(($in_charset == 'GBK' || $in_charset == 'GB2312') && $out_charset == 'UTF-8')
			{
				return gbk_to_utf8($str);
			}
			return $str;
		}
	}
}

function str_charset($in_charset, $out_charset, $str_or_arr)
{
	if(is_array($str_or_arr))
	{
		foreach($str_or_arr as $k=>$v)
		{
			$str_or_arr[$k] = str_charset($in_charset, $out_charset, $v);
		}
	}
	else
	{
		$str_or_arr = iconv($in_charset, $out_charset, $str_or_arr);
	}
	return $str_or_arr;
}

function stripstr($str)
{
	return str_replace(array('..', "\n", "\r"), array('', '', ''), $str);
}

if(!function_exists('fputcsv'))
{
	function fputcsv(&$fp, $array, $delimiter = ',', $enclosure = '"')
	{
		$data = $enclosure.implode($enclosure.$delimiter.$enclosure, $array).$enclosure."\n";
		return fwrite($fp, $data);
	}
}

function random($length, $chars = '0123456789')
{
	$hash = '';
	$max = strlen($chars) - 1;
	for($i = 0; $i < $length; $i++)
	{
		$hash .= $chars[mt_rand(0, $max)];
	}
	return $hash;
}

function set_cookie($var, $value = '', $time = 0)
{
	$time = $time > 0 ? $time : ($value == '' ? PHP_TIME - 3600 : 0);
	$s = $_SERVER['SERVER_PORT'] == '443' ? 1 : 0;
	$var = COOKIE_PRE.$var;
	$_COOKIE[$var] = $value;
	if(is_array($value))
	{
		foreach($value as $k=>$v)
		{
			setcookie($var.'['.$k.']', $v, $time, COOKIE_PATH, COOKIE_DOMAIN, $s);
		}
	}
	else
	{
		setcookie($var, $value, $time, COOKIE_PATH, COOKIE_DOMAIN, $s);
	}
}

function get_cookie($var)
{
	$var = COOKIE_PRE.$var;
	return isset($_COOKIE[$var]) ? $_COOKIE[$var] : false;
}



function is_date($ymd, $sep='-')
{
	if(empty($ymd)) return FALSE;
	list($year, $month, $day) = explode($sep, $ymd);
	return checkdate($month, $day, $year);
}

function is_email($email)
{
	return strlen($email) > 6 && preg_match("/^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/", $email);
}

function str_exists($haystack, $needle)
{
	return !(strpos($haystack, $needle) === FALSE);
}

function implodeids($array, $s = ',')
{
	if(empty($array)) return '';
	return is_array($array) ? implode($s, $array) : $array;
}


function check_in($id, $ids = '', $s = ',')
{
	if(!$ids) return false;
	$ids = explode($s, $ids);
	return is_array($id) ? array_intersect($id, $ids) : in_array($id, $ids);
}

function ip()
{
	if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown'))
	{
		$ip = getenv('HTTP_CLIENT_IP');
	}
	elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown'))
	{
		$ip = getenv('HTTP_X_FORWARDED_FOR');
	}
	elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown'))
	{
		$ip = getenv('REMOTE_ADDR');
	}
	elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown'))
	{
		$ip = $_SERVER['REMOTE_ADDR'];
	}
	return preg_match("/[\d\.]{7,15}/", $ip, $matches) ? $matches[0] : 'unknown';
}

function str_cut($string, $length, $dot = '...')
{
	$strlen = strlen($string);
	if($strlen <= $length) return $string;
	$string = str_replace(array('&nbsp;', '&amp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;'), array(' ', '&', '"', "'", '“', '”', '—', '<', '>', '·', '…'), $string);
	$strcut = '';
	if(strtolower(CHARSET) == 'utf-8')
	{
		$n = $tn = $noc = 0;
		while($n < $strlen)
		{
			$t = ord($string[$n]);
			if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
				$tn = 1; $n++; $noc++;
			} elseif(194 <= $t && $t <= 223) {
				$tn = 2; $n += 2; $noc += 2;
			} elseif(224 <= $t && $t < 239) {
				$tn = 3; $n += 3; $noc += 2;
			} elseif(240 <= $t && $t <= 247) {
				$tn = 4; $n += 4; $noc += 2;
			} elseif(248 <= $t && $t <= 251) {
				$tn = 5; $n += 5; $noc += 2;
			} elseif($t == 252 || $t == 253) {
				$tn = 6; $n += 6; $noc += 2;
			} else {
				$n++;
			}
			if($noc >= $length) break;
		}
		if($noc > $length) $n -= $tn;
		$strcut = substr($string, 0, $n);
	}
	else
	{
		$dotlen = strlen($dot);
		$maxi = $length - $dotlen - 1;
		for($i = 0; $i < $maxi; $i++)
		{
			$strcut .= ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];
		}
	}
	$strcut = str_replace(array('&', '"', "'", '<', '>'), array('&amp;', '&quot;', '&#039;', '&lt;', '&gt;'), $strcut);
	return $strcut.$dot;
}


function string2array($data)
{
	if($data == '') return array();
	eval("\$array = $data;");
	return $array;
}

function array2string($data, $isformdata = 1)
{
	if($data == '') return '';
	if($isformdata) $data = new_stripslashes($data);
	return addslashes(var_export($data, TRUE));
}

function hash_string($str)
{
	$str = str_pad($str, 10, 0, STR_PAD_LEFT);
	$str = base64_encode($str);
	$str = substr($str,-5,-3).substr($str,0,-2);
	return $str;
}

function url_par($par, $url = '')
{
	if($url == '') $url = URL;
	$pos = strpos($url, '?');
	if($pos === false)
	{
		$url .= '?'.$par;
	}
	else
	{
		$querystring = substr(strstr($url, '?'), 1);
		parse_str($par, $pars);
		foreach($pars as $k=>$v)
		{
			$querystring = _url_par($k, $v, $querystring);
		}
		$url = substr($url, 0, $pos).'?'.$querystring;
	}
	return $url;
}


?>